package com.luych.toolbox.data.service.service;

import com.luych.toolbox.common.enums.DataBackupPlanStatus;
import com.luych.toolbox.common.feign.intf.base.service.UserFeign;
import com.luych.toolbox.common.feign.param.data.service.DataBackupPlanParam;
import com.luych.toolbox.common.feign.view.data.service.DataAgentView;
import com.luych.toolbox.common.feign.view.data.service.DataBackupPlanView;
import com.luych.toolbox.common.feign.view.data.service.DataSourceView;
import com.luych.toolbox.common.page.PageParam;
import com.luych.toolbox.common.page.PageResult;
import com.luych.toolbox.common.service.base.BaseConvert;
import com.luych.toolbox.common.service.base.BaseService;
import com.luych.toolbox.common.service.exception.HttpException;
import com.luych.toolbox.common.service.page.SpringPageParamAdapter;
import com.luych.toolbox.common.service.page.SpringPageResultAdapter;
import com.luych.toolbox.data.service.constant.Constant;
import com.luych.toolbox.data.service.dao.DataAgentDao;
import com.luych.toolbox.data.service.dao.DataBackupHistoryDao;
import com.luych.toolbox.data.service.dao.DataBackupPlanDao;
import com.luych.toolbox.data.service.dao.DataSourceDao;
import com.luych.toolbox.data.service.entity.DataAgent;
import com.luych.toolbox.data.service.entity.DataBackupPlan;
import com.luych.toolbox.data.service.entity.DataSource;
import com.luych.toolbox.data.service.job.DataBackupPlanExecuteJob;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class DataBackupPlanService
        extends BaseService<DataBackupPlanView, DataBackupPlanParam, DataBackupPlan>
        implements ApplicationListener<ApplicationReadyEvent> {
    private static final Logger LOGGER = LoggerFactory.getLogger(DataBackupPlanService.class);

    private static final BaseConvert<DataBackupPlanParam, DataBackupPlan> dataBackupPlanParamToEntity = DataBackupPlan::new;
    private static final BaseConvert<DataBackupPlan, DataBackupPlanView> dataBackupPlanEntityToView = DataBackupPlanView::new;
    private static final BaseConvert<DataSource, DataSourceView> dataSourceEntityToView = DataSourceView::new;
    private static final BaseConvert<DataAgent, DataAgentView> dataAgentEntityToView = DataAgentView::new;

    private final Boolean rescheduleWhenStart;

    private final Scheduler scheduler;

    private final DataBackupPlanDao dataBackupPlanDao;
    private final DataBackupHistoryDao dataBackupHistoryDao;
    private final DataSourceDao dataSourceDao;
    private final DataAgentDao dataAgentDao;

    private final UserFeign userFeign;

    @Autowired
    public DataBackupPlanService(@Value("${spring.quartz.rescheduleWhenStart:false}") Boolean rescheduleWhenStart,
                                 Scheduler scheduler,
                                 DataBackupPlanDao dataBackupPlanDao,
                                 DataBackupHistoryDao dataBackupHistoryDao,
                                 DataSourceDao dataSourceDao,
                                 DataAgentDao dataAgentDao,
                                 UserFeign userFeign) {
        super(dataBackupPlanDao, dataBackupPlanParamToEntity, dataBackupPlanEntityToView);
        this.rescheduleWhenStart = rescheduleWhenStart;
        this.scheduler = scheduler;
        this.dataBackupPlanDao = dataBackupPlanDao;
        this.dataBackupHistoryDao = dataBackupHistoryDao;
        this.dataSourceDao = dataSourceDao;
        this.dataAgentDao = dataAgentDao;
        this.userFeign = userFeign;
    }

    @Override
    protected DataBackupPlanView fill(DataBackupPlanView view) {
        Optional<DataBackupPlan> dataBackupPlanOpt = dataBackupPlanDao.findById(view.getId());
        dataBackupPlanOpt.map(DataBackupPlan::getDataSourceId).flatMap(dataSourceDao::findById).map(dataSourceEntityToView).ifPresent(view::setDataSource);
        dataBackupPlanOpt.map(DataBackupPlan::getDataAgentId).flatMap(dataAgentDao::findById).map(dataAgentEntityToView).ifPresent(view::setDataAgent);
        dataBackupPlanOpt.map(DataBackupPlan::getOwnerId).map(userFeign::get).ifPresent(view::setOwner);
        return super.fill(view);
    }

    private JobKey getJobKey(String id) {
        return new JobKey(id, DataBackupPlanExecuteJob.class.getName());
    }

    private JobDetail getJobDetail(String id) {
        Map<String, Object> jobParam = new HashMap<String, Object>() {{
            this.put("id", id);
        }};
        return JobBuilder.newJob(DataBackupPlanExecuteJob.class)
                .withIdentity(this.getJobKey(id))
                .usingJobData(new JobDataMap(jobParam))
                .build();
    }

    private Trigger getJobTrigger(String id) {
        DataBackupPlan dataBackupPlan = dataBackupPlanDao.findById(id).orElseThrow(() ->
                new HttpException(HttpStatus.NOT_FOUND, Constant.DATA_BACKUP_PLAN_NOT_FOUND));
        return TriggerBuilder.newTrigger()
                .withIdentity(id, DataBackupPlanExecuteJob.class.getName())
                .withSchedule(CronScheduleBuilder.cronSchedule(dataBackupPlan.getCron()))
                .build();
    }

    @Override
    public DataBackupPlanView save(DataBackupPlanParam param) {
        // check corn
        if (!CronExpression.isValidExpression(param.getCron())) {
            throw new HttpException(HttpStatus.BAD_REQUEST, Constant.DATA_BACKUP_PLAN_SAVE_CRON_ERROR);
        }
        // check
        DataSource dataSource = dataSourceDao.findById(param.getDataSourceId()).orElseThrow(() ->
                new HttpException(HttpStatus.NOT_FOUND, Constant.DATA_SOURCE_NOT_FOUND));
        DataAgent dataAgent = dataAgentDao.findById(param.getDataAgentId()).orElseThrow(() ->
                new HttpException(HttpStatus.NOT_FOUND, Constant.DATA_AGENT_NOT_FOUND));

        // save
        DataBackupPlan dataBackupPlanParam = dataBackupPlanParamToEntity.apply(param);
        dataBackupPlanParam.setStatus(DataBackupPlanStatus.LOADING);
        DataBackupPlan dataBackupPlanResult = dataBackupPlanDao.save(dataBackupPlanParam);
        return this.fill(dataBackupPlanEntityToView.apply(dataBackupPlanResult));
    }

    private void setStatus(String id, DataBackupPlanStatus status) {
        DataBackupPlan dataBackupPlan = dataBackupPlanDao.findById(id).orElseThrow(() ->
                new HttpException(HttpStatus.NOT_FOUND, Constant.DATA_BACKUP_PLAN_NOT_FOUND));
        dataBackupPlan.setStatus(status);
        dataBackupPlanDao.save(dataBackupPlan);
    }

    @Override
    public DataBackupPlanView create(DataBackupPlanParam param) {
        Assert.notNull(param.getDataSourceId(), "Param dataSourceId can't be empty");
        Assert.notNull(param.getDataAgentId(), "Param dataAgentId can't be empty");
        Assert.notNull(param.getName(), "Param name can't be empty");
        Assert.notNull(param.getFile(), "Param file can't be empty");
        Assert.notNull(param.getCron(), "Param cron can't be empty");
        Assert.notNull(param.getOwnerId(), "Param ownerId can't be empty");

        // check file
        Optional<DataBackupPlan> dataBackupPlanOpt = dataBackupPlanDao.findByDataAgentIdAndFile(param.getDataAgentId(), param.getFile());
        if (dataBackupPlanOpt.isPresent()) {
            throw new HttpException(HttpStatus.CONFLICT, String.format(Constant.DATA_BACKUP_PLAN_SAVE_FILE_USED, param.getFile()));
        }

        DataBackupPlanView view = this.save(param);

        try {
            scheduler.scheduleJob(this.getJobDetail(view.getId()), this.getJobTrigger(view.getId()));
            view.setStatus(DataBackupPlanStatus.ENABLE);
            this.setStatus(view.getId(), DataBackupPlanStatus.ENABLE);
        } catch (SchedulerException e) {
            view.setStatus(DataBackupPlanStatus.EXCEPTION);
            this.setStatus(view.getId(), DataBackupPlanStatus.EXCEPTION);
            throw new IllegalStateException(e);
        }

        return view;
    }

    @Override
    public DataBackupPlanView modify(DataBackupPlanParam param) {
        Assert.notNull(param.getId(), "Param id can't be empty");
        Assert.notNull(param.getDataSourceId(), "Param dataSourceId can't be empty");
        Assert.notNull(param.getDataAgentId(), "Param dataAgentId can't be empty");
        Assert.notNull(param.getName(), "Param name can't be empty");
        Assert.notNull(param.getFile(), "Param file can't be empty");
        Assert.notNull(param.getCron(), "Param cron can't be empty");
        Assert.notNull(param.getOwnerId(), "Param ownerId can't be empty");

        // check file
        Optional<DataBackupPlan> dataBackupPlanOpt = dataBackupPlanDao.findByDataAgentIdAndFile(param.getDataAgentId(), param.getFile());
        if (dataBackupPlanOpt.isPresent() && !dataBackupPlanOpt.get().getId().equals(param.getId())) {
            throw new HttpException(HttpStatus.CONFLICT, String.format(Constant.DATA_BACKUP_PLAN_SAVE_FILE_USED, param.getFile()));
        }

        DataBackupPlanView view = this.save(param);

        try {
            scheduler.deleteJob(this.getJobKey(view.getId()));
            scheduler.scheduleJob(this.getJobDetail(view.getId()), this.getJobTrigger(view.getId()));
            view.setStatus(DataBackupPlanStatus.ENABLE);
            this.setStatus(view.getId(), DataBackupPlanStatus.ENABLE);
        } catch (SchedulerException e) {
            view.setStatus(DataBackupPlanStatus.EXCEPTION);
            this.setStatus(view.getId(), DataBackupPlanStatus.EXCEPTION);
            throw new IllegalStateException(e);
        }

        return view;
    }

    @Override
    public void remove(String id) {
        int used = 0;
        used += dataBackupHistoryDao.countByDataBackupPlanId(id);
        if (used > 0) {
            throw new HttpException(HttpStatus.FORBIDDEN, Constant.DATA_BACKUP_PLAN_DELETE_REJECT_USED);
        }

        try {
            scheduler.deleteJob(this.getJobKey(id));
        } catch (SchedulerException e) {
            throw new IllegalStateException(e);
        }

        dataBackupPlanDao.deleteById(id);
    }

    public void setEnable(String id) {
        DataBackupPlan dataBackupPlan = dataBackupPlanDao.findById(id).orElseThrow(() ->
                new HttpException(HttpStatus.NOT_FOUND, Constant.DATA_BACKUP_PLAN_NOT_FOUND));

        if (!DataBackupPlanStatus.DISABLE.equals(dataBackupPlan.getStatus())) {
            throw new HttpException(HttpStatus.FORBIDDEN, Constant.DATA_BACKUP_PLAN_ENABLE_STATUS_ERROR);
        }

        try {
            scheduler.resumeJob(this.getJobKey(id));
        } catch (SchedulerException e) {
            throw new IllegalStateException(e);
        }

        dataBackupPlan.setStatus(DataBackupPlanStatus.ENABLE);
        dataBackupPlanDao.save(dataBackupPlan);
    }

    public void setDisable(String id) {
        DataBackupPlan dataBackupPlan = dataBackupPlanDao.findById(id).orElseThrow(() ->
                new HttpException(HttpStatus.NOT_FOUND, Constant.DATA_BACKUP_PLAN_NOT_FOUND));

        if (!DataBackupPlanStatus.ENABLE.equals(dataBackupPlan.getStatus())) {
            throw new HttpException(HttpStatus.FORBIDDEN, Constant.DATA_BACKUP_PLAN_DISABLE_STATUS_ERROR);
        }

        try {
            scheduler.pauseJob(this.getJobKey(id));
        } catch (SchedulerException e) {
            throw new IllegalStateException(e);
        }

        dataBackupPlan.setStatus(DataBackupPlanStatus.DISABLE);
        dataBackupPlanDao.save(dataBackupPlan);
    }

    public PageResult<DataBackupPlanView> pageByKeyword(PageParam pageParam, String keyword) {
        Page<DataBackupPlan> page;
        if (StringUtils.isEmpty(keyword)) {
            page = dataBackupPlanDao.findAll(new SpringPageParamAdapter(pageParam));
        } else {
            page = dataBackupPlanDao.findByNameLike("%" + keyword + "%", new SpringPageParamAdapter(pageParam));
        }
        PageResult<DataBackupPlan> pageResult = new SpringPageResultAdapter<>(page);
        return pageResult.convert(dataBackupPlanEntityToView).convert(this::fill);
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        if (Boolean.TRUE.equals(rescheduleWhenStart)) {
            List<DataBackupPlan> dataBackupPlans = dataBackupPlanDao.findByStatusNot(DataBackupPlanStatus.DISABLE);
            for (DataBackupPlan dataBackupPlan : dataBackupPlans) {
                try {
                    scheduler.deleteJob(this.getJobKey(dataBackupPlan.getId()));
                    scheduler.scheduleJob(this.getJobDetail(dataBackupPlan.getId()), this.getJobTrigger(dataBackupPlan.getId()));
                    this.setStatus(dataBackupPlan.getId(), DataBackupPlanStatus.ENABLE);
                } catch (SchedulerException e) {
                    this.setStatus(dataBackupPlan.getId(), DataBackupPlanStatus.EXCEPTION);
                    throw new IllegalStateException(e);
                }
            }
        }
    }
}
